const drawButton = document.getElementById('draw-button');
const cardDisplay = document.getElementById('card-display');
const drawSound = document.getElementById('draw-sound');
const suits = ['♠','♣','♦','♥'];
const values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
let history = Array(10).fill('--');
let countdownInterval;
let isFirstClick = true;

drawButton.addEventListener('click', () => {
    if (isFirstClick) {
        startCountdown();
        isFirstClick = false;
    }
});

function drawCard() {
    const suitIndex = Math.floor(Math.random() * suits.length);
    const suit = suits[suitIndex];
    const value = values[Math.floor(Math.random() * values.length)];
    const card = `${value}${suit}`;
    
    cardDisplay.style.transform = 'rotateY(180deg)';
    setTimeout(() => {
        cardDisplay.innerHTML = `<span class="value">${value}</span><span class="suit">${suit}</span>`;
        cardDisplay.style.transform = 'rotateY(0deg)';
        cardDisplay.className = suitIndex > 1 ? 'red' : '';
    }, 250);

    updateHistory(value, suit, suitIndex);
}

function updateHistory(value, suit, suitIndex) {
    history.shift();
    history.push({ value, suit, suitIndex });

    const historyList = document.getElementById('history-list');
    historyList.innerHTML = '';
    history.forEach(item => {
        const li = document.createElement('li');
        if (item === '--') {
            li.textContent = item;
        } else {
            li.innerHTML = `<span class="value">${item.value}</span><span class="suit">${item.suit}</span>`;
            li.className = item.suitIndex > 1 ? 'red' : '';
        }
        historyList.appendChild(li);
    });
}

function startCountdown() {
    let timeLeft = 10000; // 10秒
    drawButton.disabled = true;
    drawButton.classList.remove('active');
    drawButton.textContent = '抽取中...';

    countdownInterval = setInterval(() => {
        timeLeft -= 10;
        drawButton.textContent = `下次抽取: ${(timeLeft / 1000).toFixed(2)} 秒`;

        if (timeLeft <= 0) {
            clearInterval(countdownInterval);
            drawSound.play(); // 播放音效
            drawCard();
            drawButton.disabled = false;
            drawButton.classList.add('active');
            drawButton.textContent = '开始抽取';
            startCountdown();
        }
    }, 10);
}
